# coding: utf-8
import tensorflow as tf
import numpy as np
from PIL import Image  # 替换scipy.misc.toimage
import os

# 使用Keras API加载MNIST数据集
(train_images, train_labels), (test_images, test_labels) = tf.keras.datasets.mnist.load_data()


# 预处理函数：归一化并转换为float32
def preprocess(images):
    return images.astype(np.float32) / 255.0


# 预处理训练数据
train_images = preprocess(train_images)
# 创建保存目录
save_dir = 'MNIST_data/raw/'
os.makedirs(save_dir, exist_ok=True)  # 自动处理目录存在性检查
# 保存前20张图片
for i in range(20):
    # 获取并处理图像数据
    image_array = train_images[i] * 255  # 反归一化为0-255范围
    img = Image.fromarray(image_array.astype(np.uint8))  # 转换为PIL图像

    # 保存文件
    filename = os.path.join(save_dir, f'mnist_train_{i}.jpg')
    img.save(filename)
print(f'Successfully saved images to: {save_dir}')